package yagwl.service.util.db;

import java.util.logging.Logger;

import yagwl.service.util.NumberUtil;

/**
 * Generates id's for database entities. Used only for id's that are visible to
 * the user, e.g.: account id. Access check must be performed for user-entered
 * id's.
 * 
 * Id's consist of an object code, followed by digits based on time stamp,
 * followed by 1 digit error detection code.
 */
public class IdGenerator {
  private static final Logger log = Logger.getLogger(IdGenerator.class
      .getName());

  /**
   * 
   * @param objectCode
   *          2 digit code for the object
   * @param length
   *          total length should be between 10 and 19 digits
   * @return
   */
  public static long getLong(int objectCode, int length) {
    if (objectCode < 10 || objectCode > 99 || length < 10 || length > 19)
      return 0L;
    long time = System.currentTimeMillis();
    long mod = 1L;
    for (int i = 3; i < length; i++) {
      mod *= 10;
    }
    time %= mod;
    long id = objectCode * mod + time % mod;

    // add error detection digit
    long temp = id;
    int sum = 0;
    while (temp != 0) {
      sum += (int) (temp % 10);
      temp /= 10;
    }
    temp = id * 10 + (10 - sum % 10);
    log.info(Long.toString(temp));
    return temp;
  }

  public static void main(String[] a) {
    log.info(NumberUtil.toString(getLong(13, 18), '-', 1, 2, 3, 4, 3));
  }
}
